package com.manner.groupon.utils;

import cn.hutool.crypto.digest.MD5;

import java.util.Map;
import java.util.TreeMap;

public class StrUtil {

    public static Boolean verify(Map<String, Object> map, String key) {
        String signStr = getSignStr(map);
        signStr = signStr + "&key=" + key;
        String sign = MD5.create().digestHex(signStr);

        if (sign.equalsIgnoreCase(String.valueOf(map.get("sign")))) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    public static String getSignStr(Map<String, Object> map) {
        StringBuffer str = new StringBuffer();
        TreeMap<String, Object> treeMap = new TreeMap<>(map);
        for (Map.Entry<String, Object> entry : treeMap.entrySet()) {
            if (entry.getValue() == null) {
                continue;
            }
            if (entry.getValue() instanceof String && String.valueOf(entry.getValue()).equals("")) {
                continue;
            }
            if (entry.getKey().equals("sign")) {
                continue;
            }
            if (str.length() != 0) {
                str.append("&");
            }
            str.append(entry.getKey()).append("=").append(entry.getValue());
        }
        return String.valueOf(str);
    }

}
